package com.example.springbootdemo2023.core.interceptors;

import com.alibaba.fastjson.JSON;
import com.example.springbootdemo2023.core.util.MyJWTUtil;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 模块名称：token验证拦截器
 * 模块类型：
 * 编码人：高靖博
 * 创建时间：2023/3/1
 * 联系电话：18587388612
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        System.out.println("--------------------------"+request.getRequestURL());
        System.out.println("--------------------------"+request.getRemoteAddr());

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");

        // 所有的token都要放在请求头中  header
        String token = request.getHeader("token");

        //验证
        if(token==null||token==""){

            Map<String,String> json = new HashMap<>();
            json.put("msg","认证失败，token不存在！");
            json.put("code","-1");
            PrintWriter writer = response.getWriter();
            writer.write(JSON.toJSONString(json));
            writer.flush();
            writer.close();
            return false;
        }else{// 验证

            boolean verify = MyJWTUtil.verify(token);

            if(verify){
                return true;
            }else{
                Map<String,String> json = new HashMap<>();
                json.put("msg","认证失败，token失效！");
                json.put("code","-1");
                PrintWriter writer = response.getWriter();
                writer.write(JSON.toJSONString(json));
                writer.flush();
                writer.close();
                return false;
            }

        }


    }
}
